const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verify = require('../../auth/verify')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')


/**
 * @description 文章管理
 */
module.exports = function () {
    const that = this
    /**
     * @description query数据
     * @type {{}|*}
     */
    const query = this.getQueryData(this.request.url)
    /**
     * @description 授权
     */
    const authorization = this.request.headers.authorization
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'GET').then(function () {
        /**
         * @description 授权验证
         */
        if (that.isDef(authorization)) {
            return verify(authorization)
        } else {
            return Promise.reject(new Error('缺少Authorization！'))
        }
    }).then(function (data) {
        if (data.type === 3) {
            /**
             * @description 查询条数
             */
            if (isNaN(parseInt(query.articleId))) {
                return Promise.reject(new Error('缺少文章Id！'))
            } else if (!query.status || typeof query.status !== 'string') {
                return Promise.reject(new Error('无效的Status！'))
            } else if (query.status.toUpperCase() !== 'NORMAL' && query.status.toUpperCase() !== 'CHECK') {
                return Promise.reject(new Error('Status的值应该是(NORMAL|CHECK)之间！'))
            } else {
                return Promise.resolve()
            }
        } else {
            return Promise.reject(new Error('您权限不足，请联系管理员！'))
        }
    }).then(function () {
        /**
         * @description 查询文章
         */
        return dataBase.connect(sql.SQL_SELECT_ARTICLE_STATUS_ONE(query.articleId))
    }).then(function (result) {
        /**
         * @description 检查数据是否有效
         */
        if (that.isUnDef(result[0])) {
            return Promise.reject(new Error('无效的文章Id！'))
        } else {
            return Promise.resolve(result[0])
        }
    }).then(function (result) {
        /**
         * @description 检查状态
         */
        const currentStatus = result.status
        const currentStatusText = `${currentStatus === 'NORMAL' ? '上架' : '下架'}`
        if (currentStatus === query.status.toUpperCase()) {
            that.response.outPrintError(`改文章已处于${currentStatusText}状态，无需更改！`)
        } else {
            /**
             * @description 更新状态
             */
            return dataBase.connect(sql.SQL_UPDATE_ARTICLE_STATUS_ONE(query.articleId, query.status.toUpperCase()))
        }
    }).then(function () {
        /**
         * @description 输出
         */
        that.response.outPrintData({}, '操作成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}